package com.cat.simulation;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/sort-matrix-by-diagonals/?envType=daily-question&envId=2025-08-28
 * @create 2025/8/28 18:11
 * @since JDK17
 */

public class Solution02 {
    public int[][] sortMatrix(int[][] grid) {
        int n = grid.length, m = grid[0].length, nm = n + m - 1;
        List<Integer> list = new ArrayList<>();
        for (int k = 0, x = 0, y = m - 1; k < nm; k++) {
            list.clear();
            for (int i = x, j = y; i < n && j < m; i++, j++) {
                list.add(grid[i][j]);
            }
            if (y > 0) {
                list.sort((o1, o2) -> o1 - o2);
            } else {
                list.sort((o1, o2) -> o2 - o1);
            }
            for (int i = x, j = y, idx = 0; i < n && j < m; i++, j++, idx++) {
                grid[i][j] = list.get(idx);
            }
            if (y > 0) {
                y--;
            } else {
                x++;
            }
        }

        return grid;
    }
}
